// 全局Vue对象
let _Vue = null;
// 路由模式：是否是hash模式
let _isHash = true;

export default class VueRouter {
  static install(Vue) {
    // 判断当前插件是否已经被安装
    if (VueRouter.install.installed) {
      return;
    }
    VueRouter.install.installed = true;
    // 把Vue构造函数记录到全局
    _Vue = Vue;
    // 把创建Vue实例时候传入的router对象注入到Vue实例中
    _Vue.mixin({
      beforeCreate() {
        // 此处的this指向Vue实例
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router;
          this.$options.router.init();
        }
      },
    });
  }

  constructor(options) {
    // 记录路由模式是否是hash模式
    _isHash = options.mode !== "history";
    this.options = options;
    this.routeMap = {};
    let defaultPath = "/";
    if (_isHash) {
      defaultPath = window.location.hash.replace("#", "") || "/";
    } else {
      defaultPath = window.location.pathname;
    }
    console.log(defaultPath);
    this.data = _Vue.observable({
      current: defaultPath,
    });
  }

  createRouteMap() {
    // 遍历所有路由规则，解析成键值对形式保存到routeMap中
    this.options.routes.forEach(route => {
      this.routeMap[route.path] = route.component;
    });
  }

  init() {
    this.createRouteMap();
    this.initComponents(_Vue);
    this.initEvent();
  }

  initComponents(Vue) {
    Vue.component("router-link", {
      props: {to: String},
      // template: '<a :href="to"><slot></slot></a>',
      render(h) {
        return h(
          "a",
          {
            attrs: {href: this.to},
            on: {
              click: this.clickHandler,
            },
          },
          [this.$slots.default]
        );
      },
      methods: {
        clickHandler(e) {
          if (_isHash) {
            window.location.hash = this.to;
          } else {
            // 更改浏览器地址
            history.pushState({}, "", this.to);
            // current是响应式事件，它被改变后会调用router-view中渲染的组件
            this.$router.data.current = this.to;
          }
          // 阻止浏览器默认事件
          e.preventDefault();
        },
      },
    });

    const _this = this;
    Vue.component("router-view", {
      render(h) {
        // 当 current 路径变化时，会重新渲染组件
        const component = _this.routeMap[_this.data.current];
        return h(component);
      },
    });
  }

  initEvent() {
    // 监听浏览器前进后退
    window.addEventListener("popstate", () => {
      this.data.current = window.location.pathname;
    });

    // 监听URL片段标识符变化
    window.addEventListener("hashchange", () => {
      const path = window.location.hash.replace("#", "");
      this.data.current = path;
    });
  }
}
